//
//  EventViewController.swift
//  FMRadio
//
//  Created by 范东 on 2022/7/26.
//

import UIKit
import FDUIKit
import FDNetwork
import MediaPlayer
import JXSegmentedView

class HomeViewController: BaseViewController {
    
    var dataArray = [RadioResponseModelRadio]()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // Do any additional setup after loading the view.
        view.addSubview(tableView)
        tableView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        headerRefresh()
    }
    
    @objc func headerRefresh(){
        FDNetwork.GET(url: "http://ioscndeveloper.cn/radio/radio_list_update.json", param: [:]) { result in
            let resultDict = result as! [String:Any]
            let radio = RadioResponseModel.deserialize(from: resultDict)
            self.dataArray = radio?.radio ?? [RadioResponseModelRadio]()
            self.tableView.reloadData()
            self.refreshControl.endRefreshing()
        } failure: { error in
            self.refreshControl.endRefreshing()
        }
        
    }
    
    lazy var tableView: UITableView = {
        let tableView = UITableView(frame: .zero, style: .plain)
        tableView.delegate = self
        tableView.dataSource = self
        tableView.refreshControl = refreshControl
        tableView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: 50, right: 0)
        return tableView
    }()
    
    lazy var refreshControl: UIRefreshControl = {
        let refreshControl = UIRefreshControl(frame: .zero)
        refreshControl.addTarget(self, action: #selector(headerRefresh), for: .valueChanged)
        return refreshControl
    }()
    
}

extension HomeViewController: UITableViewDelegate,UITableViewDataSource{
    func numberOfSections(in tableView: UITableView) -> Int {
        1
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        dataArray.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        var cell = tableView.dequeueReusableCell(withIdentifier: NSStringFromClass(UITableViewCell.classForCoder()))
        if cell == nil {
            cell = UITableViewCell(style: .subtitle, reuseIdentifier: NSStringFromClass(UITableViewCell.classForCoder()))
        }
        cell?.textLabel?.text = dataArray[indexPath.row].name
        cell?.detailTextLabel?.text = dataArray[indexPath.row].desc
        return cell!
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        
        let model = dataArray[indexPath.row]
        
        let sceneDelegate = UIApplication.shared.connectedScenes.first?.delegate as! SceneDelegate
        let tabBarC = sceneDelegate.window?.rootViewController as! TabBarController
        tabBarC.nowPlayingView?.model = model
        tabBarC.nowPlayingView?.playState = .playing
        
        FDAudioPlayerManager.defaultManager.play(url: model.url)
        var image = UIImage(named: model.name)
        if image == nil {
            image = UIImage(systemName: "radio")
        }
        let artwork = MPMediaItemArtwork(boundsSize: image?.size ?? .zero) { size in
            return image ?? UIImage()
        }
        MPNowPlayingInfoCenter.default().nowPlayingInfo = [MPMediaItemPropertyTitle:model.name,MPMediaItemPropertyArtist:model.desc,MPMediaItemPropertyArtwork:artwork]
        
        do {
            try AVAudioSession.sharedInstance().setActive(true)
            try AVAudioSession.sharedInstance().setCategory(.playback)
        } catch let error {
            debugPrint(error)
        }
        
        let nowPlayVC = NowPlayingViewController()
        nowPlayVC.model = model
        let nav = TUINavigationController(rootViewController: nowPlayVC)
//        nav.modalPresentationStyle = .fullScreen
        present(nav, animated: true, completion: nil)
    }
}

extension HomeViewController: JXSegmentedListContainerViewListDelegate {
    func listView() -> UIView {
        return view
    }
}
